#include <stdio.h>
#include "LinkTree.h"

// 文件系统读取
#include <dirent.h>
#include <string.h>

void PrintDirent(void *s)
{
    char *name = (char *)s;
    printf("|___%s\n", name);
}

void ExploreDirectory(const char * path, LTNode *node)
{
    DIR *dir = opendir(path);
    if (dir == NULL)
    {
        printf("%s: 路径不正确!\n", path);
        return;
    }
    // 读取文件夹流
    struct dirent *d;
    while ((d = readdir(dir)) != NULL)
    {
        if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0)
        {
            continue;
        }
        
        // 创建一个新的树节点，将文件的名称作为节点名称
        LTNode *fileNameNode = CreateTreeNode(d->d_name);
        ConnectBranch(node, fileNameNode);
        // 如果是文件夹，递归查找显示
        if (d->d_type == 4)
        {
            // 拼接路径
            char nextPath[100] = {0};
            strcpy(nextPath, path);
            strcat(nextPath, "/");
            strcat(nextPath, d->d_name);
            ExploreDirectory(nextPath, fileNameNode);
        }
    }
    closedir(dir);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("未输入路径\n");
        return -1;
    }
    const char *filepath = argv[1];

    LTree filetree;
    InitTree(&filetree);

    ExploreDirectory(filepath, filetree.root);
    TravelTree(&filetree, PrintDirent);

    FreeTree(&filetree, NULL);

    return 0;
}